#include <updatethread.h>
#include <debuglog.h>
#include <QMutex>
#include <QFile>
#include <QSettings>
#include <QtScript>
#include <QDateTime>

UpdateThread::UpdateThread(QObject *parent){
    isRun = true;
    isFirst = true;
    log = new DebugLog();
}

void UpdateThread::run(){
    log->writelog("启动更新线程");

    // 配置文件路径
    QString dir = QCoreApplication::applicationDirPath();
    QString filename = dir + "/EPOS.ini";
    QString uptime = "";
    QFile file(filename);
    if (file.exists()) {
        // 读取配置信息
        QSettings settings(filename, QSettings::IniFormat);
        settings.beginGroup("system");
        uptime = settings.value("updatetime").toString();
        settings.endGroup();
    }

    while (isRun) {
        try{
            if(isFirst){
                emit updateSignal();
            }
            else{
                QDateTime date = QDateTime::currentDateTime();
                QString timeString = date.toString("hh:mm");
                if(timeString == uptime){
                    emit updateSignal();
                }

            }
        }
        catch (QString exception){
            log->warnLog("更新线程错误：" + exception);
        }
        sleep(10);
    }
    log->writelog("更新线程结束");
}

void UpdateThread::stop(){
    QMutex locker;
    if(locker.tryLock()){
        isRun = false;
    }
    locker.unlock();
}
